package com.gwl.server.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.gwl.server.entity.SysMenu;
import com.gwl.server.entity.SysRoleMenu;
import com.gwl.server.entity.SysUser;
import com.gwl.server.lang.Const;
import com.gwl.server.lang.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

@RestController
public class AuthController extends BaseController{
    @Autowired
    Producer producer;

    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        BufferedImage image = producer.createImage(code);
        // 转换为baes64
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Image = str + base64Encoder.encode(outputStream.toByteArray());
        this.redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        return Result.succ(MapUtil.builder().
                put("token", key).
                put("captchaImg", base64Image).
                build());
    }

    @GetMapping("/sys/userInfo")
    public Result userInfo(Principal principal){
        SysUser byUserName = sysUserService.getByUserName(principal.getName());
        return Result.succ(MapUtil.builder().
                put("id", byUserName.getId()).
                put("username", byUserName.getUsername()).
                put("avatar", byUserName.getAvatar()).
                put("created", byUserName.getCreated()).
                map());
    }


}
